package com.css.chat.logic.chat.message.req;

import com.css.chat.logic.chat.SendImg;
import com.css.chat.netty.message.AbstractPacket;
import com.css.chat.netty.message.FileUpload;
import com.css.chat.netty.message.PacketType;
import io.netty.buffer.ByteBuf;
import javafx.scene.image.Image;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author zyj
 * @description
 * @date 2019/8/1 15:36
 **/
public class ImgChatToUser extends AbstractPacket {

    private long toUserId;

    private FileUpload fileUpload;

    public FileUpload getFileUpload() {
        return fileUpload;
    }

    public void setFileUpload(FileUpload fileUpload) {
        this.fileUpload = fileUpload;
    }

    public long getToUserId() {
        return toUserId;
    }

    public void setToUserId(long toUserId) {
        this.toUserId = toUserId;
    }


    public ImgChatToUser(){}

    public ImgChatToUser(File file){
        String fileName = file.getName();
        String[] strArray = fileName.split("\\.");
        int suffixIndex = strArray.length -1;
        String type = strArray[suffixIndex];

        fileUpload = new FileUpload();
        fileUpload.setFileName(fileName);
        fileUpload.setFileType(type);
        fileUpload.setBytes(getBytesByFile(file));
        fileUpload.setBase64Str(fileToBase64Str(file));
    }

    @Override
    public void readBody(ByteBuf buf) {
        this.toUserId = buf.readLong();
        this.fileUpload = readFile(buf);

    }

    @Override
    public void writeBody(ByteBuf buf) {
        buf.writeLong(this.toUserId);
        writeFile(buf, fileUpload);

    }

    @Override
    public PacketType getPacketType() {
        return PacketType.REQFRIENDSENDIMG;
    }

    @Override
    public void execPacket() {
        SendImg.getInstance().receiveFriendPrivateMessage(toUserId, new Image(""));
    }

    /**
    * @Description: file转byte
    * @Param: [filePath]
    * @return: byte[]
    * @Author: zyj
    * @Date: 2020/3/2
    */
    public static byte[] getBytesByFile(File file) {
        try {
            //获取输入流
            FileInputStream fis = new FileInputStream(file);

            //新的 byte 数组输出流，缓冲区容量1024byte
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            //缓存
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            //改变为byte[]
            byte[] data = bos.toByteArray();
            //
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
